import random
from django.db import models

# From NoPBX
from nopbx.core.models import BaseModule
from nopbx.dialplan.models import Extension
from nopbx.infrastructure.models import Location

###############################################################################

class BaseAccountManager(models.Manager):
    def get_by_natural_key(self, email):
        return self.get(email = email)

class BaseAccount(BaseModule):
    """
    Standard elements for an account
    """
    email       = models.EmailField(unique = True)
    extension   = models.ForeignKey(Extension, blank = True, null = True)
    location    = models.ForeignKey(Location, blank = True, null = True)

    objects = BaseAccountManager()
    class Meta:
        abstract = True

    def natural_key(self):
        return self.email



###############################################################################

class Person(BaseAccount):
    """
    Just as the name implies, a person.  Information that applies to a specific human.
    """
    first_name  = models.CharField(max_length = 100)
    last_name   = models.CharField(max_length = 100)

    # Long distance information
    ld_code   = models.PositiveIntegerField(unique = True, blank = True, null = True, help_text = 'Five digit code for user to call long distance (Randomly generated if left blank).')
    ld_access = models.PositiveSmallIntegerField(default = 10, help_text = 'Access level for long distance calls.')

    # SIP Account Settings
    sip_enabled  = models.BooleanField(default = False, verbose_name = 'Enable SIP')
    sip_username = models.CharField(max_length = 50, blank = True, null = True, verbose_name = 'Username', unique = True)
    sip_password = models.CharField(max_length = 50, blank = True, null = True, verbose_name = 'Password')

    class Meta:
        ordering = ['last_name', 'first_name']
        unique_together = ['last_name', 'first_name']
        verbose_name = 'Person'
        verbose_name_plural = 'People'

    def __unicode__(self):
        return '%s, %s' % (self.last_name, self.first_name)

    def save(self, force_insert = False, force_update = False):
        # Store these as NULL, not blank (Because multiple blanks aren't unique!)
        if (self.sip_username == ""): self.sip_username = None
        if (self.sip_password == ""): self.sip_password = None

        # Generate a random LD Code if one wasn't given
        if (self.ld_code == None):
            self.ld_code = random.randint(10000,99999)
        super(Person, self).save(force_insert, force_update)



###############################################################################

class Department(BaseAccount):
    """
    Department information.  Not too much here...
    """
    name = models.CharField(max_length = 100, unique = True)

    people = models.ManyToManyField(Person, blank = True, null = True)

    class Meta:
        ordering = ['name']

    def __unicode__(self):
        return self.name


